import { ElMessage } from "element-plus";
import router from "@/router";
import { useUserStore } from "@/stores/user";
import { getProfileAPI } from "./apis/user";
import type { RouteRecordRaw } from "vue-router";
import { asyncRoutes } from "./router/asyncRoutes";
import { useMenuStore } from "./stores/menu";

//路由白名单
const WHITE_LIST = ["/login", "/404"];

//处理一级路由
const getFirstRoutePerms = (permissions: string[]) => {
    const tempArr = permissions.map((item) => item.split(':')[0])
    //数组去重
    return Array.from(new Set(tempArr))
}

// 处理二级路由权限数据
const getSecondRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 根据权限筛选出匹配的路由
const getRoutes = (
  firstRoutePerms: string[],  // 一级路由权限集合
  secondRoutePerms: string[], // 二级路由权限集合
  asyncRoutes: RouteRecordRaw[] // 所有的动态路由数据
) => {
    console.log(firstRoutePerms, secondRoutePerms, asyncRoutes);
      // 超级管理员，不做筛选，返回所有路由信息
  if(firstRoutePerms.includes('*')){
    return [...asyncRoutes]
  }
  // 过滤出一级路由
  const firstRoutes = asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.meta!.permission!)
  })
    console.log('筛选后的一级路由', firstRoutes);
      // 基于筛选的一级路由，继续筛选二级路由
  const lastRoutes = firstRoutes.map(route => {
    return {
      ...route,
      // 筛选二级路由
      children: route.children?.filter(v=> secondRoutePerms.includes(v.meta!.permission!))
    }
  })
  return lastRoutes
}



//路由导航守卫
router.beforeEach(async(to, from, next) => {
    const store = useUserStore()
    //判断是否为token
    if (store.token) {
        //有token 放行
        next()
        const store = useUserStore()
        //如果没有用户信息,发送请求获取,并保存到store中
        if (!store.profile.id) {
            const res = await getProfileAPI()
            store.setProfile(res.data)
            const menus = getFirstRoutePerms(res.data.permissions)
            //console.log('menus', menus);
           const smenus = getSecondRoutePerms(res.data.permissions)
          // console.log('smenus', smenus)
           // const lastRoutes = getRoutes(menus, smenus, asyncRoutes)
           // console.log('lastRoutes', lastRoutes);
            
            //1.获取匹配的路由
            const perRoutes = getRoutes(menus, smenus, asyncRoutes)
            //2.遍历匹配的路由,动态添加到路由表中
            perRoutes.forEach(route => {
                //动态添加路由
                router.addRoute(route as RouteRecordRaw)
            })
               // 3. 保存侧栏菜单路由
               const menuStore = useMenuStore()
               menuStore.setMenuList(perRoutes as RouteRecordRaw[])
            //动态添加路由后的固定用法
            next({...to})
        }
    } else {
        if (WHITE_LIST.includes(to.path)) {
            //白名单 放行
            next()
        } else {
            //没有token 跳转到登录页
            ElMessage.error("请先登录")
            next("/login")
        }
    }
})